package com.idreems.zakerlike.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import net.youmi.android.AdManager;
import net.youmi.android.banner.AdSize;
import net.youmi.android.banner.AdView;
import net.youmi.android.banner.AdViewLinstener;

import opens.components.http.ImageRequest;

import com.huewu.pla.pinterest.internal.ImageWrapper;
import com.idreems.zakerlike.MyApplication;
import com.idreems.zakerlike.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.widget.LinearLayout;
import android.widget.Toast;

public class Util {
    public static final boolean printLog = true;
    public static final String LOG_TAG ="log";
    
    // flurry
    public static final String kFlurryKey = "9XSJCT9862G4439BHX3Y";
    public static final String kFlurryEventOnItemShare = "kFlurryEventOnItemShare";
    public static final String kFlurryEventOnChannelEntry = "kFlurryEventOnEnterChannel";
    public static final String kFlurryEventOnLargeImageSaved = "kFlurryEventOnLargeImageSaved";

    public static final String YOUMI_APP_ID = "5a1e7b0b03892899";
    public static final String YOUMI_APP_SECRET = "37b5bfd2282d505d";
    
    private static final String kAppGooglePlayUrlPrefix = "https://play.google.com/store/apps/details?id=";

    public static String getGooglePlayAppUrl(String packageName) {
        return kAppGooglePlayUrlPrefix + packageName;
    }

    /**
     * delete file or path
     * 
     * @param fileOrDirectory
     */
    public static void deleteRecursive(File fileOrDirectory) {
        if (fileOrDirectory.isDirectory())
            for (File child : fileOrDirectory.listFiles())
                deleteRecursive(child);
        fileOrDirectory.delete();
    }

    /**
     * Returns a boolean indicating whether this file can be found on the underlying file system.
     * 
     * @param fileName
     * @return
     */
    public static boolean fileExist(String fileName) {
        return new File(fileName).exists();
    }

    /*
     * share imagewrapper
     */
    public static void share(ImageWrapper wrapper, Activity context) {
        if (wrapper == null || context == null) {
            return;
        }
        try {
            boolean noImage = TextUtils.isEmpty(wrapper.url);
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType(noImage ? "text/html" : "image/*");
            intent.putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.share_from) + context.getString(R.string.app_name));
            String txt = String.format(
                    "<p>%s</p> " + context.getString(R.string.share_morefun) + "<a href=\"%s\">%s</a>", wrapper.description,
                    Util.getGooglePlayAppUrl(context.getPackageName()), context.getString(R.string.app_name));
            intent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(txt));
            if (!noImage) {
                // save as file
                ImageRequest request = new ImageRequest();
                request.get(wrapper.url);
                String fileName = request.getExternalCacheFileName(context);
                Util.save(wrapper, fileName);

                intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(fileName)));
            }
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(Intent.createChooser(intent, context.getTitle()));
        } catch (Exception e) {
            Toast.makeText(context, context.getString(R.string.share_fail), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * save image in imageWrapper to file with name:fileName
     * 
     * @param wrapper
     * @param fileName
     * @return
     */
    public static boolean save(ImageWrapper wrapper, String fileName) {
        if (TextUtils.isEmpty(fileName)) {
            return false;
        }
        ImageRequest request = new ImageRequest();
        request.setCache(MyApplication.getCache());
        request.get(wrapper.url);
        request.saveCache2File(fileName);
        return true;
    }

    /**
     * save image in ImageRequest to file with name:fileName
     * 
     * @param wrapper
     * @param fileName
     * @return
     */
    public static boolean save(String url, String fileName) {
        if (TextUtils.isEmpty(fileName)) {
            return false;
        }
        ImageRequest request = new ImageRequest();
        request.setCache(MyApplication.getCache());
        request.get(url);
        request.saveCache2File(fileName);
        return true;
    }

    /**
     * delete file or directory with command line
     * 
     * @param path
     */
    public static void deleteFiles(String path) {
        File file = new File(path);

        if (file.exists()) {
            String deleteCmd = "rm -r " + path;
            Runtime runtime = Runtime.getRuntime();
            try {
                runtime.exec(deleteCmd);
            } catch (IOException e) {
            }
        }
    }

    public static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine() method. We
         * iterate until the BufferedReader return null which means there's no more data to read.
         * Each line will appended to a StringBuilder and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "/n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }

    public static ProgressDialog ShowProgressDialog(Context context, String text) {
        ProgressDialog progressDialog = new ProgressDialog(context);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        if (text != null) {
            progressDialog.setMessage(text);
        } else {
            progressDialog.setMessage(context.getString(R.string.load_data_tip));
        }
        return progressDialog;
    }

    public static void ShowTips(Context context, String conment) {
        Toast toast = Toast.makeText(context, conment, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    public static void sendEmail(Context context, String recipient, String subject, String body) {
        Intent i = new Intent(Intent.ACTION_SEND);
        i.setType("message/rfc822");
        i.putExtra(Intent.EXTRA_EMAIL, new String[] { recipient });
        i.putExtra(Intent.EXTRA_SUBJECT, subject);
        i.putExtra(Intent.EXTRA_TEXT, body);
        try {
            context.startActivity(Intent.createChooser(i, "Send mail..."));
        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(context, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
        }
    }
    
    
    /**
     * 在activity的layout中插入banner广告
     * @param activity
     * @param layoutId
     */
    public static void loadBannerAds(Activity activity,int layoutId,boolean testMode)
    {
        if (!PreferencesPro.getInstance(activity).adsOn()) {
            return;
        }
      //初始化接口，应用启动的时候调用 
        //参数：appId, appSecret, 测试模式
        AdManager.getInstance(activity).init(YOUMI_APP_ID, YOUMI_APP_SECRET, testMode);
        // 广告条接口调用        
        // 将广告条adView添加到需要展示的layout控件中
        LinearLayout adLayout = (LinearLayout) activity.findViewById(layoutId);
        AdView adView = new AdView(activity, AdSize.SIZE_320x50);
        adLayout.addView(adView);

        // 监听广告条接口
        adView.setAdListener(new AdViewLinstener() {
            
            @Override
            public void onSwitchedAd(AdView arg0) {
                Log.i("YoumiSample", "广告条切换");
            }
            
            @Override
            public void onReceivedAd(AdView arg0) {
                Log.i("YoumiSample", "请求广告成功");
                
            }
            
            @Override
            public void onFailedToReceivedAd(AdView arg0) {
                Log.i("YoumiSample", "请求广告失败");
                
            }
        });
        
    }
    
}
